const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function wxPromisify(fn, type = '') {
  return function(obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function(res) {
        if (type == 'request') {
          if (res.data.code == 200) {
            resolve(res)
          } else {
            reject(res)
          }
        } else if (type == 'upfile') {
          if (JSON.parse(res.data).code == 200) {
            resolve(res)
          } else {
            reject(res)
          }
        } else {
          resolve()
        }

      }
      obj.fail = function(res) {
        reject(res)
      }

      fn(obj)
    })
  }
}
/**
 * 关闭弹窗
 * @param {*} contex 上下文环境
 */
const popClose = (contex) => {
  contex.setData({
    my_pop: ''
  })
}
/**
 * 控制弹窗的跳转
 * @param {*} e 
 */
const popGo = (e) => {
  console.log(e.currentTarget.dataset.type)
  const type = e.currentTarget.dataset.type;
  if (type == 'daily') {
    wx.navigateTo({
      url: '../coupons/coupons'
    })
  } else {
    wx.navigateTo({
      url: '../myCoupons/myCoupons'
    })
  }
}

//扫码获取参数
const getUrlValue = url => {
  console.log("getUrlValue")
  console.log(url)
  var res = url;
  var qs = (res.length > 0 ? res.substring(1) : ""),
    args = {},
    items = qs.length ? qs.split("&") : [],
    item = null,
    name = null,
    value = null,
    i = 0,
    len = items.length;
  for (i = 0; i < len; i++) {
    item = items[i].split("=");
    name = decodeURIComponent(item[0]);
    value = decodeURIComponent(item[1]);
    if (name.length) {
      args[name] = value;
    }
  }
  return args;
}
//函数节流
function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }

  let _lastTime = null

  // 返回新的函数
  return function() {
      let _nowTime = +new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments) //将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}

module.exports = {
    formatTime: formatTime,
    wxPromisify: wxPromisify,
    getUrlValue: getUrlValue,
    throttle: throttle,
    popClose,
    popGo
}